const express = require("express");
const router = express.Router();
const { success, failure, NotFoundError } = require("../utils/response");
const { Course } = require("../models");
/**
 * 查询课程列表
 * GET/
 */
router.get("/", async function (req, res, next) {
  try {
    const query = req.query;
    const currentPage = Math.abs(Number(query.currentPage)) || 1;
    // 每页显示多少条数据，如果不传，那就显示10条
    const pageSize = Math.abs(Number(query.pageSize)) || 10;
    const offset = (currentPage - 1) * pageSize;

    if (!query.categoryId) {
      throw new Error("获取课程");
    }

    const condition = {
      attributes: {
        exclude: ["categoryId", "UserId", "content"],
      },
      where: {
        categoryId: query.categoryId,
      },
      order: [["id", "desc"]],
      limit: pageSize,
      offset: offset,
      pageSize
    };

    const { count, rows } = await Course.findAndCountAll(condition);

    success(res, "获取首页查询成功", {
      courses: rows,
      pagination: {
        total: count,
        currentPage,
      },
    });
  } catch (error) {
    // 如果发生错误，返回错误信息
    failure(res, error);
  }
});

module.exports = router;
